package com.match.plugin.disruptor;

import java.util.concurrent.ThreadFactory;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.jfinal.plugin.IPlugin;
import com.lmax.disruptor.EventFactory;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.YieldingWaitStrategy;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
import com.match.common.model.dto.MatchOrder;
import com.match.plugin.disruptor.exception.MyHandlerException;
import com.match.plugin.disruptor.factory.OrderFactory;
import com.match.plugin.disruptor.handler.MatchHandler;
import com.match.plugin.disruptor.handler.OutDepthHandler;

/**
 * @ClassName: DisruptorConfig
 * @Description: TODO(Disruptor配置)
 */
public class DisruptorPlugin implements IPlugin {
	
	public static RingBuffer<MatchOrder> ringBuffer;
	
//	BlockingWaitStrategy:这是默认的策略。使用锁与条件进行数据的监控与唤醒。因为涉及到线程的切换，BlockingWaitStrategy策略是最省CPU,但是在高并发的状态下性能最差。
//	SleepingWaitStrategy: 对CPU的使用也是保守，会在循环中不断地等待数据。它会先进行自旋等待，如果不成功，则会使用Thread.yield()让出CPU，并最终使用LockSupport.parkNanos(1)进行线程休眠。典型的使用场景异步日志。
//	YieldingWaitStrategy:适用于低延迟的场景。消费者线程会不断循环监控缓冲区变化。
//	BusySpinWaitStrategy:最疯狂的等待策略，会吃掉所有的CPU资源，只有在对延迟非常苛刻的场合可以考虑使用。
//	ProducerType.MULTI:多生产者
	public DisruptorPlugin() {
		EventFactory<MatchOrder> factory = new OrderFactory();
		int ringBufferSize = 1024 * 1024;
		
		ThreadFactory disruptorThreadPool = new ThreadFactoryBuilder().setNameFormat("DisruptorThreadPool").build();
		Disruptor<MatchOrder> disruptor = new Disruptor<MatchOrder>(factory, ringBufferSize, disruptorThreadPool, ProducerType.MULTI, new YieldingWaitStrategy());
		disruptor.setDefaultExceptionHandler(new MyHandlerException());// Disruptor异常统计
		// 单线处理撮合, 并行处理盘口和订单薄
//		EventHandlerGroup<MatchOrder> eventHandlerGroup = 
		disruptor.handleEventsWithWorkerPool(new MatchHandler()).then(new OutDepthHandler());
//		SequenceBarrier barriers = eventHandlerGroup.asSequenceBarrier();//序列协调者
		ringBuffer = disruptor.getRingBuffer();
		disruptor.start();
		
		
	}

	@Override
	public boolean start() {
		System.err.println("DisruptorPlugin启动成功!");
		return true;
	}

	@Override
	public boolean stop() {
		System.err.println("DisruptorPlugin启动失败!");
		return true;
	}
}
